# 导入 Django 认证装饰器和渲染函数
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib import messages
from core.forms.student_form import StudentForm
# 导入学生模型
from core.models.student import Student
from core.models.daily_attendance import DailyAttendance
from ..models import ClassInfo
from core.models.student_class_enrollment import StudentClassEnrollment
from core.models.log import OperationLog
from .utils import get_no_homework_count, get_warning, get_classes
from datetime import date



# 学生创建视图
@login_required
def student_create(request):
    # 获取用户管理的班级
    user_classes = get_classes(request.user)
    if not user_classes.exists():
        messages.error(request, "您没有管理的班级，无法添加学生")
        return redirect('core:student_list')
    
    if request.method == 'POST':
        form = StudentForm(request.POST)
        if form.is_valid():
            student = form.save()
            # 自动将学生添加到所有管理的班级
            for class_info in user_classes:
                StudentClassEnrollment.objects.create(
                    student=student,
                    class_id=class_info,
                    enrollment_date=date.today(),
                    is_active=True
                )
            messages.success(request, f'学生 {student.name} 创建成功！已自动添加到您管理的班级')
            # 记录创建日志
            OperationLog.objects.create(
                user=request.user,
                operation_type='create',
                content_type='student',
                object_id=student.id,
                object_name=student.name,
                ip_address=request.META.get('REMOTE_ADDR'),
                details=f'创建学生: {student.name}, 学号: {student.id}'
            )
        return redirect('core:student_list')
    else:
        form = StudentForm()
    
    return render(request, 'student/student_form.html', {'form': form, 'title': '添加学生'})

# 学生更新视图
@login_required
def student_update(request, pk):
    user = request.user
    user_classes = get_classes(user)
    student = get_object_or_404(Student, pk=pk)
    # 检查学生是否属于当前用户管理的班级
    if not student.classes.filter(id__in=user_classes.values_list('id', flat=True)).exists():
        messages.error(request, '您没有权限编辑此学生信息')
        return redirect('core:student_list')
    
    if request.method == 'POST':
        form = StudentForm(request.POST, instance=student, user=request.user)
        if form.is_valid():
            student = form.save()
            messages.success(request, f'学生 {student.name} 更新成功！')
            # 记录更新日志
            OperationLog.objects.create(
                user=request.user,
                operation_type='update',
                content_type='student',
                object_id=student.id,
                object_name=student.name,
                ip_address=request.META.get('REMOTE_ADDR'),
                details=f'更新学生信息: {student.name}'
            )
        return redirect('core:student_list')
    else:
        form = StudentForm(instance=student, user=request.user)
    return render(request, 'student/student_form.html', {'form': form, 'title': '编辑学生'})

# 学生删除视图
@login_required
def student_delete(request, pk):
    user = request.user
    user_classes = get_classes(user)
    student = get_object_or_404(Student, pk=pk)
    # 检查学生是否属于当前用户管理的班级
    if not student.classes.filter(id__in=user_classes.values_list('id', flat=True)).exists():
        messages.error(request, '您没有权限删除此学生')
        return redirect('core:student_list')
    
    if request.method == 'POST':
        student_name = student.name
        student.delete()
        messages.success(request, f'学生 {student_name} 已删除')
        # 记录删除日志
        OperationLog.objects.create(
            user=request.user,
            operation_type='delete',
            content_type='student',
            object_id=student.id,
            object_name=student_name,
            ip_address=request.META.get('REMOTE_ADDR'),
            details=f'删除学生: {student_name}, 学号: {student.id}'
        )
        return redirect('core:student_list')
    return render(request, 'student/student_confirm_delete.html', {'student': student, 'title': '确认删除学生'})

# 获取学生列表的视图函数
@login_required
def student_list(request):
    """
    获取当前用户所管理班级的学生列表，并渲染到页面。
    同时显示第一个班级的名称。

    :param request: 请求对象
    :return: 渲染后的学生列表页面
    """
    user = request.user
    classes = get_classes(user)
    first_class = classes.first()
    if first_class:
        classname = first_class.grade.name + first_class.name
    else:
        classname = ''
    student_list = Student.objects.filter(classes__in=classes, studentclassenrollment__is_active=True).distinct()
    classid = classes.first().id if classes.exists() else None
    late_list = []
    for student in student_list:
        no_homework_count = get_no_homework_count(student, 'today')
        warning = get_warning(student, 'today')
        late_list.append({
            'student_id': student.id,
            'name': student.name,
            'student_id_number': student.id,
            'gender': student.gender,
            'gender_display': student.get_gender_display(),
            'age': student.age,
            'contact_info': student.contact_info,
            'home_address': student.home_address,
            'no_homework_count': no_homework_count,
            'warning': warning
        })
     
    return render(request, 'student/student_list.html', 
                            {'late_list':late_list,
                            'classname': classname,
                            'total_count':student_list.count(),
                            'classid':classid,
                            'title': f'{classname} 学生列表' if classname else '学生列表'})
